﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using DACU.Tools;
using DACU.VkontakteApi.Collections;
using DACU.VkontakteApi.Enums;

namespace DACU.VkontakteApi
{
	class VKRequest
	{
		public const int RequestCount = 5;
		public const int LoginTryCount = 2;

		public static string GetResponse(string url,int reqCount = RequestCount,int loginCount = LoginTryCount)
		{
			if (!VKApi.IsLogged) return "";
			HttpWebRequest request;
			WebResponse resp = null;
			StreamReader reader=null;
			string returnValue = "";
			try
			{
				request = (HttpWebRequest)WebRequest.Create(url);
				resp = request.GetResponse();
				Stream stream = resp.GetResponseStream();
				if (stream == null) return "";
				reader = new StreamReader(stream);
				returnValue = reader.ReadToEnd();
			}
			catch
			{
				throw;
			}
			finally
			{
				if (resp != null) resp.Close();
				if (reader != null) reader.Close();
			}
			if (returnValue.Contains("error"))
			{
				VKException ex = VKException.ParseResponse(returnValue);
				if (ex.ErrorCode == 5)
				{
					VKApi.Login();
					if (loginCount > 0)
						GetResponse(url, loginCount: --loginCount);
				}
				else
					throw ex;
			}
			return returnValue;
		}

		public static string MethodResponse(string method, VKParametrCollection param = null, VKFields fields = VKFields.None, VKResponseFormats responseFormat = VKResponseFormats.None)
		{
			if (!VKApi.IsLogged) return "";
			var coll = new VKParametrCollection
			           	{
			           		{"api_id", VKApi.AppId},
			           		{"format", responseFormat == VKResponseFormats.None ? VKApi.VKResponseFormat.ToString() : responseFormat.ToString()},
			           		{"method", method},
			           		{"v", VKApi.VKApiVersion}
			           	};
			string fieldsString = "";
			if(fields!= VKFields.None)
			{
				coll.Add("fields", fields.ToTrimString());
				fieldsString = "&fields=" + fields.ToTrimString();
			}
			if(param!=null && param.Count>0)
				param.ForEach(coll.Add);
			return GetResponse(URLTemplates.GetApiUrl(
				VKApi.AppId,
				fieldsString,
				VKApi.VKResponseFormat,
				method,
				VKApi.Session.Id,
				Utils.Get_sig(
					VKApi.CurrentUserId,
					coll,
					VKApi.Session.Secret),
				param==null?"":param.ToFormatedString(true),
				VKApi.VKApiVersion
				));
		}
	}
}
